(function($) {
  var UA = navigator.userAgent,
    isAndroid = /android|adr/gi.test(UA),
    isIos = /iphone|ipod|ipad/gi.test(UA) && !isAndroid,
    isWeixin = /MicroMessenger/gi.test(UA),
    isQQ = /QQ\/\d/gi.test(UA),
    isUnabledInstall = isWeixin || isQQ,
    isMobile = isAndroid || isIos;
  var downLoad = {
    handle: function(data) {
      var _self = this;
      $('#btn_download').on('click', function() {
        _self.install(data);
      });
    },
    dataHandle: function(dataObj) {
      var version = dataObj.version,
        build = dataObj.build,
        size = Number(dataObj.fsize) / 1024 / 1024,
        sizeNumber = Math.round(parseFloat(size) * 100) / 100,
        unixTime = new Date(Number(dataObj.created_at) * 1000),
        commonTime = unixTime.format('yyyy-MM-dd HH:mm');
      var resultObj = {
        id: dataObj.id,
        token: dataObj.token,
        type: dataObj.type,
        iconUrl: dataObj.icon_url,
        name: dataObj.name,
        version: version,
        build: build,
        size: sizeNumber,
        time: commonTime,
        systemName: dataObj.system_prefer_storage_name
      };
      // console.log('--------', resultObj);
      return resultObj;
    },
    appDataHandle: function(data) {
      var str = '',
        _self = this;
      var obj = _self.dataHandle(data);
      str =
        '瑜版挸澧犻悧鍫熸拱: ' +
        obj.version +
        ' (Build ' +
        obj.build +
        ')&nbsp; 閺傚洣娆㈡径褍鐨? ' +
        obj.size +
        ' MB&nbsp;<br> 閺囧瓨鏌婃禍锟? ' +
        obj.time;
      return str;
    },
    logicHandle: function(data, type) {
      var _self = this;
      //   let typeData = {},
      //     appObj = {};
      //   if (data.app) {
      //     typeData = data.app;
      //   }
      //   if (data.combo_app) {
      //     typeData = data.combo_app;
      //   }
      //   if (data.app && data.combo_app) {
      //     typeData = data.app.type == type ? data.app : data.combo_app;
      //   }
      //   appObj = _self.dataHandle(typeData);
      //   return appObj;
      return data.type != type && data.combo ? data.combo : data;
    },
    imgHandle: function(data) {
      // console.log(data, isAndroid);
      var _self = this,
        dImg = $('#dImg'),
        IconWarp = $('.icon-warp'),
        iosVersion = $('#iosVersion'),
        androidVersion = $('#androidVersion'),
        softwareVersion = $('#softwareVersion'),
        datePublished = $('#datePublished'),
        appObj = {},
        iosStr = '',
        androidStr = '',
        appType = '';
      if (isMobile) {
        if (isAndroid) {
          appObj = _self.logicHandle(data, 'android');
        }
        if (isIos) {
          appObj = _self.logicHandle(data, 'ios');
        }
        _self.handle(appObj);
        console.log(appObj);
        dImg.prop('src', appObj.ico);
        IconWarp.html('<i class="icon-' + appObj.type + '"></i>' + appObj.name);
        // softwareVersion.html(
        //   appObj.version +
        //     ' (Build ' +
        //     appObj.build +
        //     ') - ' +
        //     appObj.size +
        //     ' MB'
        // );
        softwareVersion.html('瑜版挸澧犻悧鍫熸拱閿涳拷' + appObj.version);
        datePublished.html(appObj.updated_at);
      } else {
        // appObj = _self.dataHandle(data.app);
        appObj = data;
        dImg.prop('src', appObj.ico);
        IconWarp.html(appObj.name);
        softwareVersion.html('瑜版挸澧犻悧鍫熸拱閿涳拷' + appObj.version);
        datePublished.html(appObj.updated_at);
      }
      //閸掋倖鏌囩€广垺鍩涚粩顖涙Ц閸氾缚璐熼柅姘辨暏閸︽澘娼?        // if (data.combo) {
        //   var obj = _self.pageShow(data.combo);
        //   if (obj.type == 'android') {
        //     androidVersion.html(obj.str);
        //   } else {
        //     iosVersion.html(obj.str);
        //   }
        //   appType = obj.type;
        // }
        if (data.combo) {
          $('.master-section').hide();
        } else {
          if (isMobile) {
            if (isAndroid && data.type == 'ios') {
              $('.platform-matching-tips').html('閸欘亝鏁幐锟?IOS 鐠佹儳顦?).next('.actions').hide();
            }
            if (isIos && data.type == 'android') {
              $('.platform-matching-tips').html('閸欘亝鏁幐锟?Android 鐠佹儳顦?).next('.actions').hide();
            }
          }
          $('.per-type-info').hide();
        }
      new QRCode(document.getElementById('qrcodeBox'), {
        text: decodeURIComponent(window.location.href)
      });
      $('.text-black').html(window.location.href);
    },
    pageShow(dataObj) {
      var _self = this;
      var Str = _self.appDataHandle(dataObj),
        pageObj = {},
        appType = dataObj.type,
        logInfo = dataObj.changelog
          ? dataObj.changelog
          : '濞屸剝婀侀弴瀛樻煀閺冦儱绻?;
      // $('.master-section pre').html(logInfo);
      $('title').html(dataObj.name + '-fir.im');
      pageObj = {
        str: Str,
        type: appType
      };
      return pageObj;
    },
    install: function(data) {
      console.log(data);
      var _self = this;
      // console.log('娑撳娴囬妴鍌樷偓鍌樷偓锟?, data.id, data.token);
      if (isUnabledInstall) {
        $('#actions')
          .html("<p class='strong'>瀵邦喕淇?QQ 閸愬懏妫ゅ▔鏇氱瑓鏉炶棄绨查悽锟?/p>")
          .css('marginTop', '0px');
        $('.release-info').hide();
        $('.pattern').hide();
        $('.name').css('marginBottom', '0px');
        $('.wechat_tip_content').html(
          "<div class='wechat_tip'><i class='triangle-up'></i>鐠囬鍋ｉ崙璇插礁娑撳﹨顫?br/>闁瀚ㄩ垾婊冩躬濞村繗顫嶉崳銊﹀ⅵ瀵偓閳ワ拷</div>"
        );
      } else {
        if (data.type == 'android') {
          //   $('#andDown')
          //     .prop(
          //       'href',
          //       `http://download.fir.im/apps/${data.id}/install?download_token=${
          //         data.token
          //       }`
          //     )
          //     .click();
          window.location.href = data.app;
        } else if (data.type == 'ios') {
          var action = $('#actions'),
            btnBox = $('#btn_download'),
            systemName = data.systemName;
          //   var url = encodeURIComponent(
          //     `https://download.fir.im/apps/${data.id}/install?download_token=${
          //       data.token
          //     }`
          //   );
          window.location =
            'itms-services://?action=download-manifest&url=' + data.app;
          btnBox.html('&nbsp;').prop('disabled', true);
          //閸旂姾娴囬崝銊ф暰
          setTimeout(function() {
            return 'tencent' === systemName
              ? btnBox.addClass('loading_ten')
              : btnBox.addClass('loading');
          }, 200);
          setTimeout(function() {
            action.html('<p>濮濓絽婀€瑰顥婇敍宀冾嚞閹革拷 Home 闁款喖婀宀勬桨閺屻儳婀?/p>');
          }, 2000);
        }
      }
    },
    getArgs: function(argName) {
      if (!argName) {
        return false;
      }
      var args = {},
        query = location.search.substring(1),
        pairs = query.split('&');
      for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos),
          value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);
        if (argName == argname) {
          return value;
        }
      }
    },
    getDload: function() {
      var _self = this;
      var code = location.pathname.split('/')[1];
      var buildId = _self.getArgs('version');
      var version=location.search;
      $.ajax({
        type: 'get',
        url: '',
        dataType: 'json',
        success: function(data) {
          if (data.code == 0) {
            _self.imgHandle(data.data);
          } else {
            document.querySelector('.icon-warp').innerHTML = data.message;
          }
        }
      });
    },
    init: function() {
      var _self = this;
      _self.getDload();
    }
  };
  downLoad.init();
})(Zepto);
/*
閺冦儲婀￠弽鐓庣础閸栵拷
 */
Number.prototype.pad2 = function() {
  return this > 9 ? this : '0' + this;
};
Date.prototype.format = function(format) {
  var it = new Date();
  var it = this;
  var M = it.getMonth() + 1,
    H = it.getHours(),
    m = it.getMinutes(),
    d = it.getDate(),
    s = it.getSeconds();
  var n = {
    yyyy: it.getFullYear(),
    MM: M.pad2(),
    M: M,
    dd: d.pad2(),
    d: d,
    HH: H.pad2(),
    H: H,
    mm: m.pad2(),
    m: m,
    ss: s.pad2(),
    s: s
  };
  return format.replace(/([a-zA-Z]+)/g, function(s, $1) {
    return n[$1];
  });
};